package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.Security;
import java.util.List;

@Component("crmRealm")
public class CRMRealm extends AuthorizingRealm { //获取认证信息
	@Autowired
	private EmployeeMapper employeeMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private PermissionMapper permissionMapper;

	@Autowired
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher){
		super.setCredentialsMatcher(credentialsMatcher);
	}

	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取token令牌中的用户名(登录的时候填)
		String principal = (String)token.getPrincipal();
		//数据库中查询出来的用户信息
		Employee employee = employeeMapper.getByName(principal);
		//判断该用户名是否存在数据库
		if (employee!=null) {
			//realName用来标志当前查询的数据是从哪个数据源中查询的,     username,password是从数据库中查询的真正的数据  ByteSource.Util.bytes将字符串转为ByteSource类型作为加密的盐
			//第一个参数是subject里面的身份信息
			return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getName()), "crmRealm");
		}
		//返回null表示账号不存在
		return null;
	}

	//获取授权信息


	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Subject subject = SecurityUtils.getSubject();
		//获取当前登录用户信息
		Employee employee = (Employee)subject.getPrincipal();
		//判断是不是超管
		if(employee.isAdmin()){
		//是超管获得所有权限
			info.addRole("admin");
			info.addStringPermission("*:*");
			return info;
		}else{
			//获取用户的角色信息
			List<String> roles = roleMapper.selectByName(employee.getId());
			info.addRoles(roles);
			//获取用户的权限信息
			List<String> permissions = permissionMapper.selectExpByEmpId(employee.getId());
			info.addStringPermissions(permissions);
		}
		return info;
	}

}